package com.studio5704website.api.security.handler;

import com.alibaba.fastjson.JSON;
import com.studio5704website.core.httpResult.HttpResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 高威
 * 用于处理没有登陆的handler
 */
@Component
public class DefaultNoAuthorizationHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        HttpResult result = new HttpResult.HttpResultBuilder()
                .statusCode(401)
                .message("请先登录！")
                .notSuccess()
                .build();
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setStatus(401);
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}
